const router = require('koa-router')()
const json = require('koa-json')
const { order } = require('../models/index')
router.prefix('/orders')


//添加订单
router.post('/add', async (ctx, next) => {

    let { runer, runPrice, goodsPrice, type, starAdress, endAdress,
        orderId, orderStatus, paymentMethod, realName, receiptRealname,
        receiptTel, receiptUsername, runerTel, userName, content, userTel,
        haveOrderTime, haveOrderMan, receiptOrderTime, latitudes, longitudes } = ctx.request.body

    await order.create({
        runer, runPrice, goodsPrice, type, starAdress,
        endAdress, orderId, orderStatus, paymentMethod, realName,
        receiptRealname, receiptTel, receiptUsername, runerTel, userName, content, userTel,
        haveOrderTime, haveOrderMan, receiptOrderTime, latitudes, longitudes
    }).then(res => {
        //res 此时为一个对象
        if (JSON.stringify(res) != '{}') { //如果返回不为空=>查找成功  反之为查找失败
            ctx.body = {
                code: 200,
                msg: '添加成功',
                data: res
            }
        } else {
            ctx.body = {
                code: 300,
                msg: '添加失败',
            }
        }

    }).catch(err => {
        ctx.body = {
            code: 400,
            msg: '添加时出现异常',
            err: err

        }
    })
})


//查找订单 全部订单或者类别订单
router.post('/findOne', async (ctx, next) => {
    let type = JSON.stringify(ctx.request.body) != '{}' ? ctx.request.body : {}
    await order.find(type).then(res => {
        // 注意 boolean([])=>true
        if (res.length) {
            ctx.body = {
                code: 200,
                msg: '查找成功',
                data: res
            }
        } else {
            ctx.body = {
                code: 300,
                msg: '查找失败'
            }
        }
    }).catch(err => {
        ctx.body = {
            code: 400,
            msg: '查找时出现异常'
        }
    })
})

//查找全部订单
router.post('/find', async (ctx, next) => {

    await order.find({}).then(res => {
        // 注意 boolean([])=>true
        if (res.length) {
            ctx.body = {
                code: 200,
                msg: '查找成功',
                data: res
            }
        } else {
            ctx.body = {
                code: 300,
                msg: '查找失败'
            }
        }
    }).catch(err => {
        ctx.body = {
            code: 400,
            msg: '查找时出现异常'
        }
    })
})



//模糊分页查询
router.post('/getPage', async (ctx, next) => {
    let page = +ctx.request.body.pageNum || 1
    let perPage = +ctx.request.body.pageSize || 8
    let orderId = ctx.request.body.orderId


    //查询总条数
    const total = await order.countDocuments({ orderId: { $regex: orderId, $options: '$i' } })
    await order.find({ orderId: { $regex: orderId, $options: '$i' } }).skip(perPage * (page - 1)).limit(perPage).then(res => {
        ctx.body = {
            code: 200,
            msg: '分页查找',
            data: res,
            uTotal: total
        }
    }).catch(err => {
        console.log(err)
    })
})

//删除
router.post('/delete', async (ctx, next) => {
    let { orderId } = ctx.request.body

    await order.findOneAndDelete({ orderId }).then(res => {
        ctx.body = {
            resut: res
        }

    }).catch(err => {
        ctx.body = {
            code: 400,
            msg: '删除时出现异常'
        }
    })
})

//批量删除
router.post('/deleteMany', async (ctx, next) => {
    // let itemCheckLists = ctx.request.body.
    let itemCheckLists = ctx.request.body.orderIds
    console.log(itemCheckLists)
    await order.deleteMany({ orderId: { $in: itemCheckLists } }).then(res => {
        ctx.body = {
            code: 200,
            msg: '删除成功',
            data: res
        }
    }).catch(err => {
        ctx.body = {
            code: 400,
            msg: '删除时出现异常'
        }
    })

})

//更新
router.post('/updata', async (ctx, next) => {
    let params = ctx.request.body

    await order.updateOne({ orderId: params.orderId },
        {
            runer: params.runer, runerTel: params.runerTel,
            orderStatus: params.orderStatus, receiptOrderTime: params.receiptOrderTime
        }).then(res => {
            ctx.body = {
                code: 200,
                msg: '更新成功',
                data: res
            }

        }).catch(err => {
            ctx.body = {
                code: 400,
                msg: '更新时出现异常'
            }
        })

})

//按照时间范围查询
router.post('/findbytime', async (ctx, next) => {
    let startTime = ctx.request.body.startTime
    let endTime = ctx.request.body.endTime
    //查询总条数
    const total = await order.countDocuments({ "haveOrderTime": { "$gte": new Date(startTime), "$lte": new Date(endTime) } })
    await order.find({
        "haveOrderTime": {
            "$gte": new Date(startTime),
            "$lte": new Date(endTime)
        }
    }).then(res => {
        ctx.body = {
            code: 200,
            msg: '查找成功',
            data: res,
            total: total
        }
    }).catch(err => {
        console.log(err)
    })
})

//传入经纬度
router.post('/updataAdress', async (ctx, next) => {
    let longitude = ctx.request.body.longitude
    let latitude = ctx.request.body.latitude
    let orderId = ctx.request.body.orderId
    let oldlongitude = "" //先前的总的经度
    let oldlatitude = "" //先前的总的纬度
    let newlongitudes = ""//要传到数据库的新的经度
    let newlatitudes = ""//要传到数据库的新的维度
    //获取之前的经纬度
    await order.find({ orderId: orderId }).then(res => {
        if (res.length) {
            oldlatitude = res[0].latitudes
            oldlongitude = res[0].longitudes
        } else {
            ctx.body = {
                code: 300,
                msg: '查找失败',
            }
        }
    }).catch(err => {
        console.log(err)
    })
    //拼接新的经纬度
    if (oldlongitude && oldlatitude) {
        newlongitudes = oldlongitude + ',' + longitude
        newlatitudes = oldlatitude + ',' + latitude
    } else {
        newlongitudes = longitude
        newlatitudes = latitude
    }

    //传入新的经纬度
    await order.updateOne({ orderId: orderId },
        {
            longitudes: newlongitudes, latitudes: newlatitudes
        }).then(res => {
            ctx.body = {
                code: 200,
                msg: '更新成功',
                data: res
            }

        }).catch(err => {
            ctx.body = {
                code: 400,
                msg: '更新时出现异常'
            }
        })


})


module.exports = router
